# -*- coding: utf-8 -*-
from xTkinter import * 
import tkFileDialog
import tkMessageBox as msgBox
import sys
import xmlrpclib
from Validation_Contraintes import *
Validateur =  ValidationContrainte()
class Vue_ReglesAffaires(Frame):
    def __init__(self,master,parent,**cnf):
        self.ListeContraintes = []
        self.ListLabels = []
        self.ListeBoutons = []
        self.ListeTable = []
        self.parent = parent
        self.master=master
        Frame.__init__(self,master,cnf)             
        self.pack(side=LEFT,anchor=NW)
        self.configure(width=800,height=600)
        self.CBTables=xCombobox(self)
        self.CBTables.setLocation(135,7)
        self.CBTables.setWidth(15)
        self.CBTables.setListWidth(25)
        self.CBTables.setListHeight(5)
        self.obtenirTables() 
        self.CBTables.setValidator(self.obtenirContraintes)
        self.CBTables.setText('<Choisir>')
        self.ID_Contraintes = 4
        self.Intervalle = None
        self.Action = None
        self.Information = None
        
        
        self.Regle()
    
    def obtenirTables(self):
        Reponse = self.parent.serveur.ObtenirListeTables(self.parent.user,self.parent.profil)
        if(Reponse[0]==1):
            self.ListeChamps = Reponse[1]
            for i in range(len(self.ListeChamps)):
                self.ListeTable.append(self.ListeChamps[i][0])
                self.CBTables.addItem(self.ListeChamps[i][0])
                self.CBTables.setText(self.ListeChamps[i][0])
        
    def obtenirContraintes(self):
        self.ListeContraintes = []
        Reponse = self.parent.serveur.ObtenirContraintes(self.CBTables.getText())
        for Label in self.ListLabels:
            Label.destroy()
        for Bouton in self.ListeBoutons:
            Bouton.destroy()
        if  self.Intervalle <> None:
            self.Intervalle.destroy()
        if  self.Action <> None:
            self.Action.destroy()
        if(Reponse[0]==1):
            self.ListeContraintes = Reponse[1]
            Position = 0
            self.ListeBoutons.append(xButton(self,text="Ajouter Declencheur",width=16, command = self.AjouterContrainte ))
            self.ListeBoutons[len(self.ListeBoutons)-1].setLocation(0,(Position+1)*25+5)
            self.Intervalle=xCombobox(self, width = 20)
            self.Intervalle.setListWidth(25)
            self.Intervalle.setListHeight(7)
            self.Intervalle.setLocation(x=125,y=25+5)
            self.Intervalle.addItem("A toutes les 10 secondes")
            self.Intervalle.addItem("A toutes les minutes")
            self.Intervalle.addItem("A toutes les heures")
            self.Intervalle.addItem("A tous les jours")
            self.Intervalle.addItem("A toutes les semaines")
            self.Intervalle.addItem("Lors dun evenement")
            self.Intervalle.setText("<Choisir>")
            
            self.Action=xCombobox(self, width = 20)
            self.Action.setListWidth(25)
            self.Action.setListHeight(7)
            self.Action.setLocation(x=275,y=25+5)
            self.Action.addItem("Afficher un rapport")
            self.Action.addItem("Avertissement")
            self.Action.setText("<Choisir>")
            
            self.Action.setValidator(self.RemplirInformation)
            
            Position = 1
            for Contrainte in self.ListeContraintes:
                pass
                try:
                    texte = Contrainte['MESSAGE_GUIDE'] 
                    texte = texte + '(' + Contrainte['OPERANDE_GAUCHE'] + '.'
                    texte = texte + Contrainte['ATTRIBUT_GAUCHE']
                    texte = texte + Contrainte['COMPARAISON']
                    texte = texte + Contrainte['OPERANDE_DROITE'] + ')'
                    self.ListLabels.append(xLabel(self,text=texte, width=len(texte)+2, anchor=SW ))
                    self.ListLabels[len(self.ListLabels)-1].setLocation(0,(Position+1)*25+5)
                except:
                    texte = "Contrainte invalide, corrigez-la"
                    self.ListLabels.append(xLabel(self,text=texte, width=len(texte)+2, anchor=SW ))
                    self.ListLabels[len(self.ListLabels)-1].setLocation(0,(Position+1)*25+5)

                self.ListeBoutons.append(xButton(self,text="Editer",width=12, command = lambda contrainte=Contrainte : self.OuvrirFenetreEdition(contrainte)))
                self.ListeBoutons[len(self.ListeBoutons)-1].setLocation(500,(Position+1)*25+5)
                self.ListeBoutons.append(xButton(self,text="Supprimer",width=12, command = lambda contrainte=Contrainte : self.SupprimerContrainte(contrainte)))
                self.ListeBoutons[len(self.ListeBoutons)-1].setLocation(600,(Position+1)*25+5)
                Position = Position + 1
                                 
        else:
          msgBox.showerror('PERP 2009 | Édition des tables', 'Une erreur est survenue!\n'+Reponse[1])
    
          
    def RemplirInformation(self):
        if (self.Action.getText() == "Afficher un rapport"):
            self.Information=xCombobox(self, width = 20)
            self.Information.setListWidth(25)
            self.Information.setListHeight(7)
            self.Information.setLocation(x=425,y=25+5)
            self.Information.addItem("Rapport 1")
            self.Information.addItem("Rapport 2")
            self.Information.setText("<Choisir>")
        else:
            if self.Information<>None:
                self.Information.destroy()
        
    def OuvrirFenetreEdition(self, Contrainte):
        root=Toplevel()
        root.geometry('550x175')
        root.grab_set()
        print Contrainte
        vi=Vue_EditionReglesAffaires(Contrainte, root,self)
        root.mainloop()
    
    
    
    def MettreAJourContrainte(self, Contrainte):
        if Contrainte['ID_CONTRAINTES'] <> '':
            print "Mise a jour" ,Contrainte
            where = {'valeur_gauche':'ID_CONTRAINTES', 'valeur_droite':Contrainte['ID_CONTRAINTES']}
            #where = " ID_CONTRAINTES = " + Contrainte['ID_CONTRAINTES']
            self.parent.serveur.MettreAJour('PERP_CONTRAINTES', Contrainte, [where])
            
        else:
            Contrainte['OPERANDE_GAUCHE'] = self.CBTables.getText()
            Contrainte['ID_CONTRAINTES'] = self.ID_Contraintes
            print "ajouter" ,Contrainte
            self.ID_Contraintes = self.ID_Contraintes + 1
            self.parent.serveur.InsererEnregistrement('PERP_CONTRAINTES', Contrainte)
        self.obtenirContraintes()
    
    def SupprimerContrainte(self, Contrainte):
        print "a effacer " , Contrainte
        #where = " where 'ID_CONTRAINTES' = " + Contrainte['ID_CONTRAINTES']
        where = {'valeur_gauche':'ID_CONTRAINTES', 'valeur_droite':Contrainte['ID_CONTRAINTES']}
        self.parent.serveur.EffacerEnregistrement('PERP_CONTRAINTES', [where])
        self.obtenirContraintes()     

    def AjouterContrainte(self):
        root=Toplevel()
        root.geometry('550x175')
        vi=Vue_EditionReglesAffaires(None, root,self)
        root.mainloop()
    
    def PlacerContrainte(self):
        pass
    
#    def Regle(self):
#        for x in range (1600/25):
#            X = x*25
#            xLabel(self, text=str(X)).setLocation(X,0)
#        for y in range (1200/25):
#            Y = y*25
#            xLabel(self, text=str(Y)).setLocation(0,Y)      

        



class Controleur:
    def __init__(self):
        self.user = 1
        self.profil = 1
        Serveur='http://localhost:8000'
        self.serveur=xmlrpclib.ServerProxy(Serveur)
        root=Tk()
        root.geometry('800x400')
        vi=Vue_ReglesAffaires(root,self)
        root.mainloop()       

Controleur = Controleur()

    
    
    
